var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jwt-simple')
var moment=require('moment')
var app = express();

app.set('port', (process.env.PORT || 7000));
app.set('jwtTokenSecret','my_secret');

app.use('/', express.static(path.join(__dirname, 'server')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//allow custom header and CORS
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, x-access-token,Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.send(200); //让options请求快速返回/
  }
  else {
    next();
  }
});


var BLOGS_FILE = path.join(__dirname, 'database/blogs.json');
var USERS_FILE = path.join(__dirname,'database/users.json');

var jwtauth=function(req,res,next){
  var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
  console.log('server receive token:'+token);
  if(token){
    try{
      var decoded =jwt.decode(token,app.get('jwtTokenSecret'))
      if(decoded.exp<=Date.now()){
        res.end('Access token has expired',400);
      }
      fs.readFile(USERS_FILE,function(err,data){
        var users=JSON.parse(data);
        users.forEach((user,index)=>{
          console.log('index user:'+user.username);
          if(user.id===decoded.iss){
            //req.session.user=user;
            console.log('select='+user.id)
            req.user=user;
            next();
          }
        })
      })
    }catch(err){
      next();
    }
  }else{
    next();
  }
};

/**
* 查询所有的blog列表
*/
app.get('/api/blogs', jwtauth,function(req, res) {
  var user = req.user;
  //console.log('get /api/blogs receive user:'+user.username);
  fs.readFile(BLOGS_FILE, function(err, data) {
    //res.setHeader('Cache-Control', 'no-cache');
    var result={
      blogs:JSON.parse(data).reverse(),
      user:user
    };
    res.json(result);
  });
});

/**
* 新增或修改blog信息，并返回blogs列表
*/
app.post('/api/blog', function(req, res) {
  //console.log(req.body);
  //var b=JSON.parse(req.body);
  var blogId=req.body.id;
  console.log("blogId="+req.body.id);
  fs.readFile(BLOGS_FILE, function(err, data) {
    var blogs = JSON.parse(data);
    if(blogId!==undefined){//存在id，则修改
      blogs.forEach((blog,index) =>{
        if(blog.id === blogId){
          blogs.splice(index,1,req.body);
        }
      })
    }else{//不存在id，则新增
      req.body.id=blogs.length+1;
      blogs.push(req.body);
    }

    fs.writeFile(BLOGS_FILE, JSON.stringify(blogs, null, 4), function(err) {
      //res.setHeader('Cache-Control', 'no-cache');
      console.log(blogs)
    res.json(blogs.reverse());
    });
  });
});

/**
* 根据id查询blog信息
*/
app.get('/api/blog/:id',function(req,res){
  var id= parseInt(req.params.id);
  fs.readFile(BLOGS_FILE,function(err,data){
    var blogs = JSON.parse(data);
    var result;
    blogs.forEach(blog => {
      if(blog.id===id){
        result=blog;
      }
    })
    res.setHeader('Cache-Control', 'no-cache');
    console.log(result);
    res.json(result);
  });
});

/**
* 根据id删除blog信息
*/
app.delete('/api/blog/:id',function(req,res){
  var id=parseInt(req.params.id);
  console.log('delete blog ,id='+id);
  fs.readFile(BLOGS_FILE,function(err,data){
    var blogs=JSON.parse(data);

    blogs.forEach((blog,index) =>{
      if(blog.id === id){
        blogs.splice(index,1);
      }
    })

    fs.writeFile(BLOGS_FILE,JSON.stringify(blogs,null,4),function(err){
      res.setHeader('Cache-Control', 'no-cache');
      res.json(blogs.reverse());
    })

  });
});

/**
* 根据用户名称查询用户信息
*/
app.get('/api/user/:username',function(req,res){
  var username=req.params.username;
  console.log('loing user id='+id);
  fs.readFile(USERS_FILE,function(err,data){
    var users=JSON.parse(data);
    var result={};
    users.forEach((user,index)=>{
      if(user.username===username){
        result=user;
      }
    })
    res.json(result);
  });
})

app.post('/api/user/login',function(req,res){
  var loginUser=req.body;
  console.log('loing user username='+loginUser.username+';'+loginUser.password);
  fs.readFile(USERS_FILE,function(err,data){
    var users=JSON.parse(data);
    var result={};
    users.forEach((user,index)=>{
      console.log('index user:'+user.username+';'+user.password);
      if(user.username===loginUser.username && user.password===loginUser.password){
        //req.session.user=user;
        console.log('select='+user)
        result=user;
      }
    })
    console.log('result='+result.id)
    if(result.id!==undefined){

        var expires=moment().add(1,'day').valueOf();
        var token=jwt.encode({
          iss:result.id,
          exp:expires
        },app.get('jwtTokenSecret'));
        res.json({
          token:token,
          expires:expires,
          user:result
        });
    }else{
      res.json(result);
    }
  })
})




app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});
